package com.example.temp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.example.common.UploadResult;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;




public class APIGWDemo
{
    private final static Logger logger = Logger.getLogger(APIGWDemo.class);

/*
   //测试环境：https://apigw-beta.huawei.com/api
   private final static String ENV ="https://apigw-beta.huawei.com/api";
   private final static String API_URL = "/thecCenter/services/thec/screengmp/addCommonData";
   private final static String AK="68c70e9c14a8b4cf84407c6b77fb4400"; //AK 测试与生产不一致
   private final static String SK="9c2755fd48cd2ea0eed46eb08e75646b"; //SK 测试与生产不一致
*/

      //生产环境 ：https://apigw-04.huawei.com/api
      private final static String ENV ="https://apigw-04.huawei.com/api";
      private final static String API_URL = "/thecCenter/services/thec/screengmp/addCommonData";
      private final static String AK="eceb259238bcc8f488d70664819e002b"; //AK 测试与生产不一致
      private final static String SK="ff30b14f0603550f1803c25e591503ad"; //SK 测试与生产不一致

    public static void main(String[] args)
    {

        String json="{\"data\":{\"barCode\":\"testxxxxx001\",\"testResult\":\"OK\"},\"dataType\": \"WPTM\",\"materialType\": \"COVER\"}";
        try {
            getRomteData(json);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void getRomteData(String json) throws IOException {
        HttpURLConnection connection = getConnection();

        OutputStream output = connection.getOutputStream();
        output.write(json.getBytes("UTF-8"));
        output.flush();
        output.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
        connection.disconnect();

       // return null;
    }

    private static HttpURLConnection getConnection() throws IOException{
        Map<String, String> header = new HashMap<String, String>();
        header=constructRequestHeader(API_URL,"POST");

        URL postUrl = new URL(ENV+API_URL);
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", header.get("Content-Type"));
        connection.setRequestProperty("X-HW-SIGN", header.get("X-HW-SIGN"));
        connection.setRequestProperty("X-HW-ACCESS-KEY", header.get("X-HW-ACCESS-KEY"));
        connection.setRequestProperty("X-HW-DATE", header.get("X-HW-DATE"));

        return connection;
    }
    public static Map<String, String> constructRequestHeader(String service, String requestMethod) {
    Date date = new Date();
    Map<String, String> header = new HashMap<String, String>();
    header.put("X-HW-ACCESS-KEY", AK);
    header.put("X-HW-DATE", dateFormat(date));
    header.put("Content-Type", "application/json;charset=utf-8");
    try {
        header.put("X-HW-SIGN", generateSign(service, requestMethod, date, AK, SK));
    } catch (NoSuchAlgorithmException noSuchAlgorithmException) {
        logger.error("Apigw create request sign error, there is no ecription algorithm. {}",
                noSuchAlgorithmException);
    } catch (UnsupportedEncodingException unsupportedEncodingException) {
        logger.error("Api crate request sign error, not support the enoding, {}", unsupportedEncodingException);
    }
    return header;
}

public static String generateSign(String service, String httpMethod, Date date,
        String appid, String token) throws NoSuchAlgorithmException, UnsupportedEncodingException {

    String sourceStr = service + "|" + httpMethod;
    sourceStr = sourceStr + "|" + dateFormat(date) + "|" + appid + "|" + token;

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    byte[] bt = sourceStr.getBytes("UTF-8");
    md.update(bt);
    String strDes = bytes2Hex(md.digest());
    return strDes;
}

public static String dateFormat(Date date) {
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String dateStr = sdf.format(date);
    dateStr = dateStr.replace("_", "T");
    dateStr = dateStr + "Z";
    return dateStr;
}

public String getDate() {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    String date = format.format(new Date());
    return date;
}

private static String bytes2Hex(byte[] bts) {
    String des = "";
    String tmp = null;
    for (int i = 0; i < bts.length; i++) {
        tmp = (Integer.toHexString(bts[i] & 0xFF));
        if (tmp.length() == 1) {
            des += "0";
        }
        des += tmp;
    }
    return des;
}
public static String dateFormat24(Date date){
    final SimpleDateFormat sdf24 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateStr = sdf24.format(date);
    return dateStr;

}
public static String beforeTime10(Date date){
    Calendar beforeTime = Calendar.getInstance();
    beforeTime.add(Calendar.MINUTE, -10);// 10分钟之前的时间
    Date beforeD = beforeTime.getTime();
    String before10 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeD);  // 前十分钟时间
    return before10;

}

public static String signBody(String body, String key) {
    String bodyBase64 = Base64.encodeBase64String(body.getBytes());
    return DigestUtils.sha256Hex(bodyBase64 + "|" + key);
}

public static String signRequest(String appId, String appKey, String serviceUri, String method, String date,
        Map<String, String> args) {

    List<String> params = null;

    if (args != null) {
        params = new ArrayList<String>(args.size());
        Map<String, String> sortMap = new TreeMap<String, String>(args);
        Set<String> keySet = sortMap.keySet();
        for (String key : keySet) {
            if (! key.startsWith("X-HW")) {
                String value = args.get(key);
                if (value != null) {
                    params.add(String.format("%s=%s", key, value));
                } else {
                    params.add(key);
                }
            }
        }
    }

    if (appKey != null) {
        String signString = null;
        if (params != null && params.size() > 0) {
            String paramString = StringUtils.join(params, "|");
            signString = StringUtils.join(new String[] { serviceUri, method, paramString, date, appId, appKey }, "|");
        } else {
            signString = StringUtils.join(new String[] { serviceUri, method, date, appId, appKey }, "|");
        }

        return DigestUtils.sha256Hex(signString);
    } else {
        return null;
    }

}
}
